package com.wifi.a007.wifiFragment;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.wifi.a007.LogPrint;
import com.wifi.a007.R;
import com.wifi.a007.ViewName;
import com.wifi.a007.json.Forecast;
import com.wifi.a007.json.Weather;
import com.wifi.a007.utile.HttpUtil;
import com.wifi.a007.utile.Utility;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by liyuanjing on 2015/9/28.
 */
public class WeatherFragment extends Fragment {

    private ScrollView weatherLayout;
    private TextView titleCity;
    private TextView     titleUpdateTime;
    private TextView     degreeText;
    private TextView     weatherInfoText;
    private LinearLayout forecastLayout;
    private TextView     aqiText;
    private TextView     pm25Text;
    private TextView     comfortText;
    private TextView     carWashText;
    private TextView     sportText;
    private ImageView bingPicImg;
    public SwipeRefreshLayout swipeRefresh;
    public DrawerLayout drawerLayout;
    private Button navButton;
    private String   mWeatherId;
    private boolean  picUpdate;





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.activity_weather,container,false);

            LogPrint.echo("main threadId:"+Thread.currentThread().getId());
        init(view);

        return view;
    }


    public void init(View  view){



        swipeRefresh = (SwipeRefreshLayout)view.findViewById(R.id.swipe_fresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        weatherLayout = (ScrollView) view.findViewById(R.id.weather_layout);
        titleCity = (TextView) view.findViewById(R.id.title_city);
        titleUpdateTime = (TextView) view.findViewById(R.id.title_update_time);
        degreeText = (TextView) view.findViewById(R.id.degree_text);
        weatherInfoText = (TextView)view. findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) view.findViewById(R.id.forecast_layout);
        aqiText = (TextView) view.findViewById(R.id.aqi_text);
        pm25Text = (TextView)view. findViewById(R.id.pm25_text);
        comfortText = (TextView)view.findViewById(R.id.comfort_text);
        carWashText = (TextView) view.findViewById(R.id.car_wash_text);
        sportText = (TextView) view.findViewById(R.id.sport_text);

        bingPicImg = (ImageView)view.findViewById(R.id.bing_pic_img);
        drawerLayout =(DrawerLayout)view.findViewById(R.id.drawer_layout);
        navButton =(Button)view.findViewById(R.id.nav_button);
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });



        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ViewName.mContext);
        String binPic= prefs.getString("bing_pic",null);
        if(binPic != null){
            Glide.with(this).load(binPic).into(bingPicImg);
         // getActivity().getWindow().setBackgroundDrawable(bingPicImg.getDrawable());
            LogPrint.echo("activity bg  set success");
        }else{

            loadBingPic();
        }
        if(getTodayTime().equals(getShareTime())){
            LogPrint.echo("pic toda init has update before");
            picUpdate=true;//今天更新过了图片就不更新了一天一次
        }else{

            LogPrint.echo("pic not update");

            picUpdate=false;
        }

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });
        String weatherString = prefs.getString("weather", null);

        if (weatherString != null) {

            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId = weather.basic.weatherId;
            showWeatherInfo(weather);

        }else{

            drawerLayout.openDrawer(GravityCompat.START);
        }



    }


    public void  requestWeather(final String weatherId){

        String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+"&key=bc0418b57b2d4918819d3974ac1285d9";

        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            navButton.post(new Runnable() {
                    @Override
                    public void run() {
                        LogPrint.toast(ViewName.mContext,"天气信息获取失败");
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {


                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);

                Log.i("weather", weather + "?????????????????");

                navButton.post(new Runnable() {
                    @Override

                    public void run() {

                        if (weather != null && "ok".equals(weather.status)) {

                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ViewName.mContext).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            mWeatherId = weather.basic.weatherId;
                            //刷新必须更新地方的id不然会回第一次打开到默认的地方数值

                            showWeatherInfo(weather);

                        } else {

                            LogPrint.toast(ViewName.mContext, "获取天气信息失败");

                        }
                        swipeRefresh.setRefreshing(false);

                    }

                });


            }
        });


        loadBingPic();

    }

    private  void showWeatherInfo(Weather weather){

        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        String degree   =weather.now.temperature+"°C";
        String weatherInfo =weather.now.more.info;
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        forecastLayout.removeAllViews();
        Log.i("forecastlist count:",weather.forecastList.size()+"");
        for(Forecast forecast : weather.forecastList){



            View view = LayoutInflater.from(ViewName.mContext).inflate(R.layout.forecast_item,forecastLayout,false);

            TextView dateText =(TextView)view.findViewById(R.id.date_text);
            TextView infoText =(TextView)view.findViewById(R.id.info_text);
            TextView maxText  =(TextView)view.findViewById(R.id.max_text);
            TextView minText  =(TextView)view.findViewById(R.id.min_text);
            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            forecastLayout.addView(view);


        }

        if(weather.aqi != null){

            aqiText.setText(weather.aqi.city.aqi);
            pm25Text.setText(weather.aqi.city.pm25);


        }
        // weatherLayout.setVisibility(View.VISIBLE);

        String comfort ="舒适度: "+ weather.suggestion.comfort.info;
        String carWash ="洗车指数: "+ weather.suggestion.carWash.info;
        String sport   ="运动建议: "+weather.suggestion.sport.info;
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        weatherLayout.setVisibility(View.VISIBLE);




    }









    private  void loadBingPic(){


            if(picUpdate){
                LogPrint.echo("pic","toDay pic has update");
                return ;
            }

        final String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {

                final String bingPic=response.body().string();
                SharedPreferences.Editor editor= PreferenceManager.getDefaultSharedPreferences(ViewName.mContext).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();

                setTime();
                LogPrint.echo("bingPic threadId:"+Thread.currentThread().getId());
                navButton.post(new Runnable() {
                    @Override
                    public void run() {

                        Glide.with(WeatherFragment.this).load(bingPic).into(bingPicImg);
                      //  getActivity().getWindow().setBackgroundDrawable(bingPicImg.getDrawable());
                        LogPrint.echo("activity bg  set success");
                    }
                });
            }
        });
    }

    private String getTodayTime(){

        java.util.Date  date=new java.util.Date();
        SimpleDateFormat simpleDateFormat= new SimpleDateFormat("y-m-d");
        String  time =simpleDateFormat.format(date);
        LogPrint.echo("todayTime",time);

        return time;

    }

    private String getShareTime(){

        SharedPreferences pres= PreferenceManager.getDefaultSharedPreferences(ViewName.mContext);
        LogPrint.echo(pres.getString("updateTime","1970-9-9"));
        return pres.getString("updateTime","1970-9-9");

    }


    private  void setTime(){

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ViewName.mContext).edit();
        java.util.Date  date=new java.util.Date();
        SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-mm-dd");
        String  time =simpleDateFormat.format(date);
        editor.putString("updateTime",time);
        editor.apply();

        picUpdate=true;
        LogPrint.echo("setTime threadId:"+Thread.currentThread().getId());





    }



}
